<template>

  <div class="form_page">
    <div class="form_title">申请详情</div>
    <component 
      v-for="(field, index) in fields" 
      :key="index" 
      :is="componentMap[field.type]" 
      :id="field.id"
      :label="field.label" 
      :value="formData[field.id]" 
      :isRequired="field.isRequired"
      @update:value="updateFormData(field.id, $event)"
    >
    </component>

    <view class=""><button type="primary" @click="addForm">动态创建一个数据</button></view>

    <view class="" style="margin-top: 30px;"><button type="primary" @click="submitForm">提交</button></view>

  </div>

</template>

<script setup>

import { ref, reactive, onMounted } from "vue";
import RadioFiled from "./component/inputForm.vue";

const formData = reactive({
});

// 映射
const componentMap = {
	radioFiled: RadioFiled
};

// 这是数据到时候是调用接口，接口直接给到的，但是拿到这个数据，我们要直接创建一个动态的 formData 变量，这样我们可以直接进行所有数据的获取
const fields = reactive ([
	{ id: 'name', label: '用户名', type: 'radioFiled', isRequired: true },
	{ id: 'email', label: '邮箱', type: 'radioFiled', isRequired: true },
	{ id: 'age', label: '年龄', type: 'radioFiled', isRequired: false }
]);

// 遍历出fields中的每个id
onMounted(() => {
  fields.forEach((field) => {
    formData[field.id] = '';
  });
  console.log('formData=======>', formData);
});

const addForm = () => {
  const newField = {
    id: 'sex',
    label: '性别',
    type: 'radioFiled',
    isRequired: true
  };
  fields.push(newField);
  formData[newField.id] = '';
};

const updateFormData = (id, value) => {
	formData[id] = value;
};

const submitForm = () => {
  const isValid = fields.every((field) => {
  if (field.isRequired && !formData[field.id]) {
    alert(`${field.label} is required`);
    return false;
  }
    return true;
  });

  if (isValid) {
    console.log('Form submitted:', formData);
  }
};

</script>

<style lang="less" scoped>

.form_page {
  position: relative;
}

</style>